package com.lagou.config;

import com.lagou.io.Resources;
import com.lagou.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;


public class XMLConfigBuilder {
    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 该方法就是将配置文件进行解析，封装Configuration
     * @param inputStream
     * @return
     */
    public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {
        // 使用dom4j解析配置文件
        Document document = new SAXReader().read(inputStream);
        // 获取跟对象
        Element rootElement = document.getRootElement();
        List<Element> list = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        for (Element element : list) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name, value);
        }

        // 创建数据源对象采用c3p0
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));

        // 将数据源信息封装到configuration中的datasource中
        configuration.setDataSource(comboPooledDataSource);

        // 解析mapper配置信息
        // 通过mapper配置信息读取对应的配置文件的路径，并解析配置文件信息到内存中
        List<Element> elementList = rootElement.selectNodes("//mapper");
        for (Element element : elementList) {
            String resource = element.attributeValue("resource");
            InputStream mappedStream = Resources.getResourcesASStream(resource);
            XMLMappedBuilder xmlMappedBuilder = new XMLMappedBuilder(configuration);
            xmlMappedBuilder.parse(mappedStream);

        }



        return  configuration;
    }
}
